<template>
  <view class="content">
    <uni-nav-bar 
      title="用户信息获取示例" 
      left-icon="back" 
      @clickLeft="handleBack"
      fixed 
      placeholder>
    </uni-nav-bar>
    
    <view class="container">
      <!-- 用户信息展示 -->
      <uni-section title="用户信息" type="line">
        <view class="user-info-container" v-if="userInfo.avatarUrl">
          <view class="user-avatar">
            <image :src="userInfo.avatarUrl" mode="aspectFill" class="avatar-img"></image>
          </view>
          <view class="user-details">
            <text class="user-nickname">{{ userInfo.nickName }}</text>
            <view class="user-meta">
              <text class="meta-item">性别: {{ genderMap[userInfo.gender] }}</text>
              <text class="meta-item">城市: {{ userInfo.city }}</text>
              <text class="meta-item">省份: {{ userInfo.province }}</text>
              <text class="meta-item">国家: {{ userInfo.country }}</text>
            </view>
          </view>
        </view>
        <view class="no-user-info" v-else>
          <text class="hint-text">请点击下方按钮获取用户信息</text>
        </view>
      </uni-section>
      
      <!-- 获取用户信息 -->
      <uni-section title="操作" type="line">
        <view class="section-content">
          <button type="primary" @click="handleGetUserProfile" :disabled="!!userInfo.avatarUrl">
            获取用户信息
          </button>
          <button type="primary" @click="handleGetUserInfo" :disabled="!!userInfo.avatarUrl">
            获取已授权用户信息
          </button>
          <button type="primary" @click="handleOpenSetting">
            打开授权设置
          </button>
          <button type="warn" @click="handleClearUserInfo">
            清除用户信息
          </button>
        </view>
      </uni-section>
      
      <!-- 权限说明 -->
      <uni-section title="权限说明" type="line">
        <view class="permission-info">
          <text class="info-text">需要用户授权才能获取详细信息</text>
          <text class="info-text">包括头像、昵称、性别、地区等</text>
        </view>
      </uni-section>
      
      <!-- 详细信息展示 -->
      <uni-section title="详细信息" type="line" v-if="userInfo.avatarUrl">
        <view class="detail-container">
          <view class="detail-item">
            <text class="detail-label">完整信息:</text>
            <scroll-view scroll-y class="detail-content">
              <text class="detail-text">{{ JSON.stringify(userInfo, null, 2) }}</text>
            </scroll-view>
          </view>
        </view>
      </uni-section>
      
      <!-- 说明 -->
      <uni-section title="说明" type="line">
        <view class="description">
          <text>\n1. getUserProfile: 推荐方式，用户每次都需要点击授权</text>
          <text>\n2. getUserInfo: 需要用户已授权，无需再次点击</text>
          <text>\n3. 包含头像、昵称、性别、地区等详细信息</text>
          <text>\n4. 如果获取失败，请检查是否已授权</text>
        </view>
      </uni-section>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
// 导入uni-ui组件
import uniNavBar from '@dcloudio/uni-ui/lib/uni-nav-bar/uni-nav-bar.vue'
import uniSection from '@dcloudio/uni-ui/lib/uni-section/uni-section.vue'

// 导入微信API封装
import { auth } from '@/utils/wechat/index.js'

// 响应式数据
const userInfo = reactive({
  avatarUrl: '',
  nickName: '',
  gender: 0,
  city: '',
  province: '',
  country: '',
  language: ''
})

const genderMap = {
  0: '未知',
  1: '男',
  2: '女'
}

// 方法
const handleBack = () => {
  uni.navigateBack()
}

// 获取用户信息（推荐方式）
const handleGetUserProfile = async () => {
  try {
    uni.showLoading({ title: '获取中...' })
    
    const res = await auth.getUserProfile({
      desc: '用于完善用户资料'
    })
    
    // 更新用户信息
    Object.assign(userInfo, res.userInfo)
    
    uni.hideLoading()
    uni.showToast({ title: '获取成功', icon: 'success' })
  } catch (err) {
    uni.hideLoading()
    console.error('获取用户信息失败:', err)
    
    if (err.errMsg && err.errMsg.includes('fail auth deny')) {
      uni.showToast({ title: '用户拒绝授权' })
    } else {
      uni.showToast({ title: '获取失败: ' + (err.errMsg || err.message) })
    }
  }
}

// 获取已授权用户信息
const handleGetUserInfo = async () => {
  try {
    uni.showLoading({ title: '获取中...' })
    
    // 先检查是否已授权
    const setting = await auth.getSetting()
    
    if (!setting.authSetting['scope.userInfo']) {
      uni.hideLoading()
      uni.showModal({
        title: '提示',
        content: '请先授权用户信息',
        confirmText: '去授权',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            handleOpenSetting()
          }
        }
      })
      return
    }
    
    const res = await auth.getUserInfo()
    
    // 更新用户信息
    Object.assign(userInfo, res.userInfo)
    
    uni.hideLoading()
    uni.showToast({ title: '获取成功', icon: 'success' })
  } catch (err) {
    uni.hideLoading()
    console.error('获取用户信息失败:', err)
    
    // 检查是否是权限问题
    if (err.errMsg && (err.errMsg.includes('auth deny') || err.errMsg.includes('auth denied'))) {
      uni.showModal({
        title: '权限不足',
        content: '请在设置中授权用户信息',
        confirmText: '去设置',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            handleOpenSetting()
          }
        }
      })
    } else {
      uni.showToast({ title: '获取失败: ' + (err.errMsg || err.message) })
    }
  }
}

// 打开授权设置页面
const handleOpenSetting = async () => {
  try {
    const res = await auth.openSetting()
    if (res.authSetting && res.authSetting['scope.userInfo']) {
      uni.showToast({ title: '授权成功' })
    } else {
      uni.showToast({ title: '请手动授权' })
    }
  } catch (err) {
    console.error('打开设置失败:', err)
    uni.showToast({ title: '打开设置失败' })
  }
}

// 清除用户信息
const handleClearUserInfo = () => {
  // 清空用户信息
  Object.keys(userInfo).forEach(key => {
    if (key === 'gender') {
      userInfo[key] = 0
    } else {
      userInfo[key] = ''
    }
  })
  
  uni.showToast({ title: '已清除' })
}
</script>

<style scoped>
.content {
  padding: 20rpx;
}

.container {
  padding-top: var(--status-bar-height);
}

.user-info-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx 20rpx;
}

.user-avatar {
  margin-bottom: 30rpx;
}

.avatar-img {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  border: 2rpx solid #eee;
}

.user-details {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.user-nickname {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.user-meta {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.meta-item {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.meta-item:last-child {
  margin-bottom: 0;
}

.no-user-info {
  padding: 60rpx 20rpx;
  text-align: center;
}

.hint-text {
  font-size: 32rpx;
  color: #999;
}

.section-content {
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.section-content button {
  margin: 0;
}

.permission-info {
  padding: 20rpx;
}

.info-text {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.detail-container {
  padding: 20rpx;
}

.detail-item {
  display: flex;
  flex-direction: column;
}

.detail-label {
  font-size: 28rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.detail-content {
  height: 300rpx;
  background-color: #f5f5f5;
  padding: 20rpx;
  border-radius: 10rpx;
}

.detail-text {
  font-size: 24rpx;
  line-height: 1.5;
  color: #333;
  font-family: monospace;
}

.description {
  padding: 20rpx;
  font-size: 28rpx;
  line-height: 1.6;
  color: #333;
}
</style>